#!/usr/bin/env python
# encoding: utf-8
"""
#-------------------------------------------------------------------#
#                   CONFIDENTIAL --- CUSTOM STUDIOS                 #     
#-------------------------------------------------------------------#
#                                                                   #
#                   @Project Name : Globallawonline                #
#                                                                   #
#                   @File Name    : ProduceSmartWordList.py                      #
#                                                                   #
#                   @Programmer   : 李建                            #
#                                                                   #  
#                   @Start Date   : 2021/2/9 11:35                 #
#                                                                   #
#                   @Last Update  : 2021/2/9 11:35                 #
#                                                                   #
#-------------------------------------------------------------------#
# Classes:用于生产智能推荐词表的类                                                          #
#                                                                   #
#-------------------------------------------------------------------#
"""
import re

import jieba
import langid
import pandas as pd


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def checkCellvalue(value=str):
        """
        用以检查每个单元格的值是否是单独的中、英文法律专业术语
        :param value: 值
        :return: True/False
        """
        TitleS = ["nan", "Glossary", "Of Commonly Used Court & Justice System", "Terminology", "(ENGLISH― HINESE)"]
        MeaninglesS = ["English", "Simplified Chinese", "Traditional Chinese"]
        uppercase = [chr(i) for i in range(65, 91)]
        if value in TitleS:
            return False
        for Meaningles in MeaninglesS:
            if Meaningles in value:
                value = value.replace(Meaningles, "")
        if value in uppercase:
            return False
        if len(value) == 0:
            return False
        else:
            return True

    @staticmethod
    def dealchineseword(word):
        """
        处理中文专业术语词
        :param word:中文专业术语词
        :return:
        """
        pass

    @staticmethod
    def dealenglishword(word, delimiters):
        """
        处理英文专业术语词
        :param word: 英文专业术语词
        :param delimiters:分割词语的符号包括" "、"/"等
        :return:
        """
        for delimiter in delimiters:
            key_list = word.split(delimiter)
            word = key_list[0]
        key = key_list[0]
        return key

    @staticmethod
    def writeintxt(keydict:dict, txtpath):
        """
        将推荐词表写入txt文件
        :param keydict:智能推荐词表的dict,value为推荐词列表list
        :param txtpath:写入的txt文件
        :return:
        """
        originaldict = {}  # 原txt文件中的推荐词表
        with open(txtpath, 'r+', encoding='utf-8') as f:
            lines = f.readlines()   # 按行读取文件
            for line in lines:
                line = line.rstrip("\n")    # 去除每行结尾的换行符
                key_list = line.split("	")  # 分隔每行推荐词
                key = key_list[0]   # 取推荐词的key
                values = [] # 推荐词的values
                for key_str in key_list[1:]:
                    key_str = key_str.rstrip(";")   # 去除最后的";"以免分割时有''
                    value_list = key_str.split(";")
                    for value in value_list:
                        values.append(value)
                originaldict[key] = values
        for key in keydict.keys():
            if originaldict.get(key, 0):
                originaldict[key] = list(set(originaldict[key] + keydict[key]))
            else:
                originaldict[key] = keydict[key]


    def dealTerminology(self, excel_path, sheet_name):
        """
        处理法律专业术语
        :param excel_path:Excel的全路径
        :param sheet_name:Excel对应的工作簿
        :return:
        """
        data_list = []  # 提取所有的专业术语列表
        english_dict = {}  # 英文词典
        chinese_dict = {}  # 中文词典
        # 读取工作簿和工作簿中的工作表
        data = pd.read_excel(excel_path, sheet_name)
        for i in range(len(data)):
            for j in range(len(data.columns)):
                value = str(data.iloc[i, j])
                isnumpy = self.checkCellvalue(value)
                if isnumpy: data_list.append(value)
        for data in data_list:
            data = data.lstrip("（")
            languageS = langid.classify(data)
            if languageS[0] == "zh":
                result = list(jieba.cut(data, cut_all=True))
                key = result[0]
                if chinese_dict.get(key, 0):
                    if data in chinese_dict[key]:
                        continue
                    chinese_dict[key].append(data)
                else:
                    chinese_dict[key] = [data]
            elif languageS[0] == "en":
                key = self.dealenglishword(data, r"( /")
                if english_dict.get(key, 0):
                    if data in english_dict[key]:
                        continue
                    english_dict[key].append(data)
                else:
                    english_dict[key] = [data]
        with open('chinese.txt', 'w+', encoding='utf-8') as f:
            for key in chinese_dict.keys():
                f.write(key + " " + ";".join(chinese_dict[key]) + "\n")
        with open('englishtext.txt', 'w+', encoding='utf-8') as f:
            for key in english_dict.keys():
                f.write(key + " " + ";".join(english_dict[key]) + "\n")


if __name__ == '__main__':
    excelpath = r"E:\工作记录\工作内容\“一带一路”项目\技术文档\智能推荐词表\法律专业术语中英文对照.xlsx"
    sheetname = "法律专业术语"
    Sample().dealTerminology(excelpath, sheetname)
